package com.jinbooks.persistence.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinbooks.entity.customer.CustomerAggregate;
import com.jinbooks.entity.customer.CustomerBasic;
import com.jinbooks.entity.customer.CustomerExtended;
import com.jinbooks.entity.customer.dto.CustomerPageDto;
import com.jinbooks.persistence.mapper.CustomerAggregateMapper;
import com.jinbooks.persistence.mapper.CustomerBasicMapper;
import com.jinbooks.persistence.mapper.CustomerExtendedMapper;
import com.jinbooks.persistence.service.CustomerAggregateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户聚合信息服务实现类
 *
 * @author wuyan
 */
@Service
public class CustomerAggregateServiceImpl extends ServiceImpl<CustomerAggregateMapper, CustomerAggregate>
        implements CustomerAggregateService {

    private static final Logger logger = LoggerFactory.getLogger(CustomerAggregateServiceImpl.class);

    private final CustomerBasicMapper customerBasicMapper;
    private final CustomerExtendedMapper customerExtendedMapper;

    public CustomerAggregateServiceImpl(CustomerBasicMapper customerBasicMapper,
                                        CustomerExtendedMapper customerExtendedMapper) {
        this.customerBasicMapper = customerBasicMapper;
        this.customerExtendedMapper = customerExtendedMapper;
    }

    @Override
    public Page<CustomerAggregate> pageList(CustomerPageDto dto) {
        return baseMapper.customerPageList(dto.build(), dto);
    }

    @Override
    public CustomerAggregate getCustomerFullInfo(String customerId, String workspaceId) {
        if (customerId == null || customerId.isEmpty()) {
            logger.warn("Customer ID is null or empty.");
            return null;
        }

        CustomerAggregate customer = baseMapper.getFullInfoById(customerId, workspaceId);
        if (customer == null) {
            logger.info("Customer with ID {} not found.", customerId);
        } else {
            logger.info("Customer with ID {} retrieved successfully.", customerId);
        }
        return customer;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCustomerFullInfo(CustomerAggregate customer) {

        // 保存基本信息
        CustomerBasic customerBasic = new CustomerBasic();
        copyProperties(customer, customerBasic);
        boolean basicResult = customerBasicMapper.insert(customerBasic) > 0;

        // 只有在基本信息保存成功后，才保存扩展信息
        if (basicResult) {
            CustomerExtended customerExtended = new CustomerExtended();
            copyProperties(customer, customerExtended);
            // 确保CustomerExtended使用与CustomerBasic相同的ID
            customerExtended.setId(customerBasic.getId());

            boolean extendedResult = customerExtendedMapper.insert(customerExtended) > 0;

            if (extendedResult) {
                logger.info("Customer with ID {} saved successfully.", customer.getId());
                return true;
            } else {
                logger.warn("Failed to save customer extended info with ID {}.", customer.getId());
                return false;
            }
        } else {
            logger.warn("Failed to save customer basic info with ID {}.", customer.getId());
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCustomerFullInfo(CustomerAggregate customer) {
        if (customer == null || customer.getId() == null || customer.getId().isEmpty()) {
            logger.warn("Customer or Customer ID is null.");
            return false;
        }

        // 更新基本信息
        CustomerBasic customerBasic = new CustomerBasic();
        copyProperties(customer, customerBasic);
        boolean basicResult = customerBasicMapper.updateById(customerBasic) > 0;

        // 更新扩展信息
        CustomerExtended customerExtended = new CustomerExtended();
        copyProperties(customer, customerExtended);
        boolean extendedResult = customerExtendedMapper.updateById(customerExtended) > 0;

        boolean result = basicResult && extendedResult;
        if (result) {
            logger.info("Customer with ID {} updated successfully.", customer.getId());
        } else {
            logger.warn("Failed to update customer with ID {}.", customer.getId());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCustomer(String customerId) {
        if (customerId == null || customerId.isEmpty()) {
            logger.warn("Customer ID is null or empty.");
            return false;
        }

        // 逻辑删除基本信息和扩展信息
        CustomerBasic customerBasic = new CustomerBasic();
        customerBasic.setId(customerId);
        customerBasic.setDeleted("y");

        boolean basicResult = customerBasicMapper.updateById(customerBasic) > 0;

        CustomerExtended customerExtended = new CustomerExtended();
        customerExtended.setId(customerId);

        boolean extendedResult = customerExtendedMapper.updateById(customerExtended) > 0;

        boolean result = basicResult && extendedResult;
        if (result) {
            logger.info("Customer with ID {} deleted successfully.", customerId);
        } else {
            logger.warn("Failed to delete customer with ID {}.", customerId);
        }
        return result;
    }

    /**
     * 拷贝CustomerAggregate对象属性到CustomerBasic对象
     * @param source 源对象CustomerAggregate
     * @param target 目标对象CustomerBasic
     */
    private void copyProperties(CustomerAggregate source, CustomerBasic target) {
        BeanUtils.copyProperties(source, target);
        // 复制基础实体属性
        target.setCreatedBy(source.getCreatedBy());
        target.setCreatedDate(source.getCreatedDate());
        target.setModifiedBy(source.getModifiedBy());
        target.setModifiedDate(source.getModifiedDate());
    }

    /**
     * 拷贝CustomerAggregate对象属性到CustomerExtended对象
     * @param source 源对象CustomerAggregate
     * @param target 目标对象CustomerExtended
     */
    private void copyProperties(CustomerAggregate source, CustomerExtended target) {
        BeanUtils.copyProperties(source, target);
        // 复制基础实体属性
        target.setCreatedBy(source.getCreatedBy());
        target.setCreatedDate(source.getCreatedDate());
        target.setModifiedBy(source.getModifiedBy());
        target.setModifiedDate(source.getModifiedDate());
    }
}